package org.example.demo;

import org.example.common.ConnUtil;
import org.example.common.DemoException;
import org.example.common.TokenHolder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @package: org.example.demo
 * @Description:
 * @author: zhangKN
 * @date: 2021-04-28 17:04:13
 * @copyright: Copyright (C) 2021
 * @version: V1.0
 */
public class TtsMain {

    private final static String appKey = "";

    private final static String secretKey = "";

    private final static int per = 0;
    private final static int spd = 5;
    private final static int vol = 5;
    private final static int pit = 5;

    private final static int aue = 6;

    public final static String url = "http://tsn.baidu.com/text2audio";

    private final static String cuid = "zkn_demo";

    public static void main(String[] args) {

    }

    public static void download(String text, String filePath) throws IOException, DemoException {
        TokenHolder holder = new TokenHolder(appKey, secretKey, TokenHolder.ASR_SCOPE);
        holder.refresh();
        String token = holder.getToken();

        // 此处2次urlencode， 确保特殊字符被正确编码
        String params = "tex=" + ConnUtil.urlEncode(ConnUtil.urlEncode(text));
        params += "&per=" + per;
        params += "&spd=" + spd;
        params += "&pit=" + pit;
        params += "&vol=" + vol;
        params += "&cuid=" + cuid;
        params += "&tok=" + token;
        params += "&aue=" + aue;
        params += "&lan=zh&ctp=1";
        // 反馈请带上此url，浏览器上可以测试
        System.out.println(url + "?" + params);

        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setConnectTimeout(5000);
        PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
        printWriter.write(params);
        printWriter.close();
        String contentType = conn.getContentType();
        if (contentType.contains("audio/")) {
            byte[] bytes = ConnUtil.getResponseBytes(conn);
            // 打开mp3文件即可播放
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            try (FileOutputStream os = new FileOutputStream(file)) {
                os.write(bytes);
            }
            System.out.println("audio file write to " + file.getAbsolutePath());
        } else {
            System.err.println("ERROR: content-type= " + contentType);
            String res = ConnUtil.getResponseString(conn);
            System.err.println(res);
        }

    }

    private static String getFormat(int aue) {
        String[] formats = {"mp3", "pcm", "pcm", "wav"};
        return formats[aue - 3];
    }

}
